package team.bluepen.supermarket.web.servlet;

import team.bluepen.supermarket.constant.Error;
import team.bluepen.supermarket.util.ServletUtil;
import team.bluepen.supermarket.web.base.DataServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户删除
 * @author Kai
 */
@WebServlet(name = "UserDeleteServlet", urlPatterns = "/api/user-delete")
public class UserDeleteServlet extends DataServlet {
    public static final String USER_ROW_PARAM = "user_row";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
        if (!checkUserRole(req)) {
            resp.sendRedirect(requestSource);
            return;
        }
        String row = req.getParameter(USER_ROW_PARAM);
        String requestSource = ServletUtil.getRefererUrl(req);
        if (row == null) {
            resp.sendRedirect(requestSource + "?error=" + Error.ERROR_NULL.getValue());
            return;
        }

        Error state = userRepository.delete(row);
        resp.sendRedirect(requestSource + "?error=" + state.getValue());
    }
}
